#!/bin/bash

# 定义颜色输出
RED='\033[31m'
GREEN='\033[32m'
YELLOW='\033[33m'
BLUE='\033[34m'
RESET='\033[0m'

# 创建日志目录
LOG_DIR="/var/log/system_maintenance"
mkdir -p $LOG_DIR
LOG_FILE="$LOG_DIR/maintenance_$(date +%Y%m%d_%H%M%S).log"

# 检查root权限
if [ "$(id -u)" != "0" ]; then
  echo -e "${RED}错误：必须使用root权限运行本脚本${RESET}" | tee -a $LOG_FILE
  exit 1
fi

# 系统基础信息检查
echo -e "\n${BLUE}====== 系统基础信息 ======${RESET}" | tee -a $LOG_FILE
{
  echo -e "${GREEN}主机名: $HOSTNAME"
  echo "系统时间: $(date)"
  echo "运行时间: $(uptime)"
  echo "系统版本: $(cat /etc/redhat-release)"
  echo "内核版本: $(uname -r)"
  echo "CPU使用率: $(top -bn1 | grep 'Cpu(s)' | sed 's/.*, *\([0-9.]*\)%* id.*/\1/' | awk '{print 100 - $1}')%"
  echo "内存使用: $(free -m | awk '/Mem/{printf "%.2f%", $3/$2*100}')"
  echo "磁盘使用:"
  df -h | grep -vE 'tmpfs|devtmpfs' | sed 's/^/  /'
} | tee -a $LOG_FILE

# 内核参数检查
echo -e "\n${BLUE}====== 内核参数检查 ======${RESET}" | tee -a $LOG_FILE
{
  echo -e "${YELLOW}当前生效参数:${RESET}"
  sysctl -a | grep -E 'net.ipv4.ip_forward|fs.file-max|net.core.somaxconn'

  echo -e "\n${YELLOW}配置文件差异检查:${RESET}"
  grep -E '^net.ipv4.ip_forward|^fs.file-max|^net.core.somaxconn' /etc/sysctl.conf
} | tee -a $LOG_FILE

# 防火墙检查
echo -e "\n${BLUE}====== 防火墙状态 ======${RESET}" | tee -a $LOG_FILE
{
  firewall-cmd --state 2>&1
  echo -e "\n${YELLOW}开放端口:${RESET}"
  firewall-cmd --list-ports
  echo -e "\n${YELLOW}开放服务:${RESET}"
  firewall-cmd --list-services
} | tee -a $LOG_FILE

# 网络信息检查
echo -e "\n${BLUE}====== 网络状态检查 ======${RESET}" | tee -a $LOG_FILE
{
  echo -e "${YELLOW}IP地址信息:${RESET}"
  ip addr show | grep 'inet ' | grep -v '127.0.0.1'

  echo -e "\n${YELLOW}路由表:${RESET}"
  ip route

  echo -e "\n${YELLOW}监听端口:${RESET}"
  ss -tulnp | grep -vE '127.0.0.1|::1'
} | tee -a $LOG_FILE

# 服务状态检查
echo -e "\n${BLUE}====== 服务状态检查 ======${RESET}" | tee -a $LOG_FILE
{
  echo -e "${YELLOW}关键服务状态:${RESET}"
  systemctl list-units --type=service --state=running |
    grep -E 'sshd|nginx|httpd|mysql|mariadb|postgresql'

  echo -e "\n${YELLOW}失败服务检测:${RESET}"
  systemctl --failed
} | tee -a $LOG_FILE

# 软件包检查
echo -e "\n${BLUE}====== 软件包检查 ======${RESET}" | tee -a $LOG_FILE
{
  echo -e "${YELLOW}可用更新:${RESET}"
  yum check-update | grep -v '^$'

  echo -e "\n${YELLOW}最近安装的软件包:${RESET}"
  rpm -qa --last | head -20
} | tee -a $LOG_FILE

# 安全审计
echo -e "\n${BLUE}====== 安全审计 ======${RESET}" | tee -a $LOG_FILE
{
  echo -e "${YELLOW}SSH登录记录:${RESET}"
  grep 'sshd' /var/log/secure | tail -10

  echo -e "\n${YELLOW}sudo使用记录:${RESET}"
  grep 'sudo:' /var/log/secure | tail -5
} | tee -a $LOG_FILE

echo -e "\n${GREEN}检查完成，完整日志请查看：$LOG_FILE${RESET}"
